﻿using System;
using System.IO;
using System.Net;
using log4net;

namespace Sherwood.Content.UpdateServices.Attachments
{
    public class TextContentOnlyAttachmentPersister<TAttachmentMeta> : IAttachmentPersister
        where TAttachmentMeta : class, IAttachmentMeta, new()
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(TextContentOnlyAttachmentPersister<TAttachmentMeta>));

        private readonly IMetaRepository _metaRepository;

        public TextContentOnlyAttachmentPersister(IMetaRepository metaRepository)
        {
            _metaRepository = metaRepository;
        }
        
        public void AddAttachment(IAttachmentMeta meta, string referenceId, string url, string fileExtension)
        {
            fileExtension = (string.IsNullOrEmpty(fileExtension) ? Path.GetExtension(url) : "." + fileExtension);
            var fileName = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()) + fileExtension;

            using (var webClient = new WebClient())
                webClient.DownloadFile(url, fileName);

            string content;
            var couldGetContent = FileContent.TryGet(fileName, out content);
            File.Delete(fileName);
            if (couldGetContent && !string.IsNullOrEmpty(content))
            {
                var attachment = meta.GetOrCreateAttachment(referenceId);
                attachment.FileName = Path.GetFileNameWithoutExtension(url) + fileExtension;
                attachment.TextContent = content;
            }
        }

        public void UpdateAttachment(IAttachmentMeta meta, IAttachment attachment, string url, string fileExtension)
        {
            AddAttachment(meta, attachment.ReferenceId, url, fileExtension);
        }

        public void DeleteAttachment(IAttachmentMeta meta, IAttachment value)
        {
            meta.DeleteAttachment(value.ReferenceId);
        }

        public void ClearAttachments(IRecord record, IClient client, string usageKey)
        {
            var meta = _metaRepository.GetMeta<TAttachmentMeta>(record.Id, client.Id, usageKey);
            if(meta != null)
                meta.ClearAttachments();
        }
    }
}